package com.mes_for_xxxxxx.task;

import cn.hutool.core.bean.BeanUtil;
import com.mes_for_xxxxxx.entity.Processflow;
import com.mes_for_xxxxxx.entity.Processflowouttime;
import com.mes_for_xxxxxx.enums.StatusEnums;
import com.mes_for_xxxxxx.service.IProcessflowService;
import com.mes_for_xxxxxx.service.IProcessflowouttimeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 定时任务，推进流程到超时表
 *
 * @author LJK
 * @description
 * @date 2024/9/10
 */
@Component
@Slf4j
public class OutTimeTaskService {
    @Autowired
    IProcessflowouttimeService processflowouttimeService;
    @Autowired
    IProcessflowService processflowService;

    @Scheduled(fixedDelay = 100000)
    @Transactional
    public void outTimeTask() {
        log.info("解决超时未推进问题---定时任务执行开始...");
        List<Processflow> outTimeTask = processflowService.outTimeTask();
        if (outTimeTask.isEmpty()) {
            log.info("无异常任务");
            return;
        }
        //报工 工序递交的数据压平

        outTimeTask.forEach(task -> {
            String desc = StatusEnums.getDescByCode(task.getStatus());
            if(Objects.isNull(task.getRemark())){
                task.setRemark("");
            }
            task.setRemark(task.getRemark() + ";在工序" + task.getThisFlow() + "超时，"+"超时状态为"+desc);
        });
        List<Processflowouttime> processflowouttimes = BeanUtil.copyToList(outTimeTask, Processflowouttime.class);
        boolean add = processflowouttimeService.saveBatch(processflowouttimes);
        boolean upd = processflowService.updateBatchById(outTimeTask);
        if (!add || !upd) {
            throw new RuntimeException("解决超时未推进问题---定时任务执行失败");
        }
        log.info("解决超时未推进问题---定时任务执行结束...");
    }

    @Scheduled(fixedDelay = 100000)
    public void addNextFlow() {
        log.info("完善工序流流程---定时任务执行开始...");
        int i = processflowService.addNextFlow();
        log.info("完善工序流流程---定时任务执行结束...,本次共完善{}条数据",i);
    }
}
